import React from 'react';

import { AddPaymentCard } from '@/features/AddPaymentCard';
import { ModalContext } from '@/shared/context/ModalContext';
import { Modals } from '@/shared/interfaces';
import { useAppDispatch, useAppSelector } from '@/shared/store';
import { Button, ButtonVariants, PaymentCard, Snackbar, Title } from '@/shared/ui';
import { useSnackbar } from 'notistack';
import { useWindowSize } from 'usehooks-ts';

import { setActiveCard } from '../../model/actions';
import { Card } from '../../model/reducer';
import { getUserActiveCard, getUserCards } from '../../model/selectors';
import cs from './Cards.module.scss';

export const Cards = () => {
  const cards = useAppSelector(getUserCards);
  const activeCard = useAppSelector(getUserActiveCard);

  const { width } = useWindowSize();
  const { openModal, setData } = React.useContext(ModalContext);
  const dispatch = useAppDispatch();

  const { enqueueSnackbar } = useSnackbar();

  const onChoose = (card: Card) => {
    dispatch(setActiveCard(card));
    enqueueSnackbar('Карта выбрана', {
      variant: 'success',
      content: (key, message) => <Snackbar id={key} message={message} size="md" variant="success" />,
    });
  };

  const onDelete = (card: Card) => {
    openModal(Modals.DeletePaymentCard);
    setData(() => card);
  };

  React.useEffect(() => {
    if (cards.length > 0 && activeCard === null) {
      dispatch(setActiveCard(cards[0]));
    }
  }, [cards.length, activeCard]);

  return (
    <div className={cs.container}>
      <section className={cs.section}>
        <Title size="l" title="Способ оплаты" />
        <Button className={cs.btn} onClick={() => openModal(Modals.AddPaymentCard)} variant={ButtonVariants.Link}>
          Добавить
        </Button>
      </section>
      <div className={cs.cards}>
        {cards?.map((card) => (
          <PaymentCard
            isActive={activeCard?.number === card.number}
            key={card.number}
            onChoose={onChoose}
            onDelete={onDelete}
            {...card}
          />
        ))}
        {width >= 1024 && <AddPaymentCard />}
        {width < 1024 && cards.length === 0 && <Title size="xs" title="Вы не добавили карту" />}
      </div>
    </div>
  );
};
